package com.shark.agentweb;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * @author: guojr
 * @date: 2019/12/5
 */
public class WebViewInterceptDialog extends AppCompatActivity
        implements DialogInterface.OnDismissListener {
    private static final String KEY_INTERCEPT_URL = "key_intercept_url";

    public static void show(Activity activity, String url) {
        Intent intent = new Intent();
        intent.setClass(activity, WebViewInterceptDialog.class);
        intent.putExtra(KEY_INTERCEPT_URL,url);
        activity.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final String url = getIntent().getStringExtra(KEY_INTERCEPT_URL);

        new AlertDialog.Builder(this)
                .setTitle("是否允许页面打开第三方应用?")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        if (isAppLink(url)) {
                            openAppLink(url);
                        } else {
                            openApp(url);
                        }
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).setOnDismissListener(this);

    }

    private boolean isAppLink(String url) {
        Uri uri = Uri.parse(url);
        return uri != null
                && SharkWeb.APP_LINK_HOST.equals(uri.getHost())
                && (url.startsWith("http") || url.startsWith("https"));
    }


    private void openApp(String url) {
        Intent intent;
        try {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            this.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "您所打开的第三方App未安装！", Toast.LENGTH_SHORT).show();
        }
    }

    private void openAppLink(String url) {
        try {
            Intent intent = new Intent(SharkWeb.APP_LINK_ACTION);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "您所打开的第三方App未安装！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        this.finish();
    }
}
